package com.bodacn.keypoint;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.ComboLineColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ComboLineColumnChartView;

import static android.content.Context.MODE_PRIVATE;
import static java.lang.Math.round;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentC extends Fragment implements View.OnClickListener, View.OnLongClickListener {
    public static String TAG=FragmentC.class.getName();
    public static final int msgFocusBarcode = 1001;
    public static final int msgGetImg=1002;
    public static final int msgPutQuestionOK=1003;
    public static final int msgPutQuestionErr=1004;
    public static final int MSG_SCANBARCODE = 9001;
    public static final int MSG_CLIPVIEW=9002;
    public static final int MSG_ANDONCALL=9003;
    public static final int MSG_ChartOver =9004;
    public static final int MSG_ERRMSG =9005;
    public static final int MSG_Spinner=9006;
    ReentrantLock reentrantLock = new ReentrantLock();
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    SQLiteDatabase tmpdb;
    //全局变量
    Toast curToast;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID;
    Button btn_find,btn_Query,btn_Select;
    ImageButton btn_editBarcode;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_PO,txt_Color,txt_Size,txt_StyleSort,txt_Depart,txt_PSXX;
    TextView txt_ClampSendNum,txt_ClampOwenNum,txt_TodayRepairNum,txt_ClampRepairNum,txt_NeedCheckInNum;
    Button btn_MarkBadPoint,btn_ClampState,btn_CheckAndonCall,btn_BatchRepair;
    EditText edt_barcode;
    JSONArray resultJSON,headJSON,detailJSON,partJson,questionJson,spinnerJSON;
    JSONArray chartJSON;
    String PrBarcode="";
    ListView detailList;
    String  selDepartNo="",selDepart="",selOrderNo="",selStyleNo="",selPO="",selColor="",selSize="",selStyleSort="",selImageFile="",selPSXX="",selManuDepartNo="",selManuDepart="";
    int MaxPieces=5;
    EditText edt_checkReal;
    TextView view_QCCode;
    DetailListAdapter detailListAdapter;
    boolean NeedCheck=false;
    private ComboLineColumnChartView mainCTColumnChart;
    private ComboLineColumnChartData mainCTColumnData;
    Spinner reasonSpinner;
    //图表标识
    private boolean hasAxes = true;
    private boolean hasPoints = true;
    private boolean hasLines = true;
    private boolean isCubic = false;
    private boolean hasLabels = false;
    //主程序回调传参--------------------------------------------开始;
    private FragmentCCallBack mFragmentCCallBack;
    /*定义一个业务接口,主程序负责实现，所以需在主程序implements中加上这个接口的引用>>>>>切记<<<<<<
    该Fragment所在Activity需要实现该接口
    该Fragment将通过此接口与它所在的Activity交互*/
    public interface FragmentCCallBack {
        // 里面传个值@param Map<String,Object>适应多种类型;
        void FragmentCWorkAndTransParams(Map<String, Object> Params);
    }

    //主程序回调传参--------------------------------------------结束;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity) context;
        if (!(activity instanceof FragmentA.FragmentACallBack)) {
            throw new IllegalStateException("MainActivity必须实现FragmentBCallBack接口");
        }
        mFragmentCCallBack=(FragmentCCallBack) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mFragmentCCallBack=null;
    }

    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean onLongClick(View view) {
        switch (view.getId()) {
            case R.id.btn_MarkBadPoint:
                MakeBadPoint("Single");
                break;
            default:
                break;
        }
        return false;
    }


    public FragmentC() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        try {
            headJSON=new JSONArray("[]");
            detailJSON=new JSONArray("[]");
            resultJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println(TAG+"onCreate-------------------------------------1");
        //创建适配器
        detailListAdapter = new DetailListAdapter(getContext());
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerC(new MainActivity.OnTransParamsListenerC() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        System.out.println(mParams);
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(this.getClass().getName(),"LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir= mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d(this.getClass().getName(),"LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (paramComm=="RefreshDetail"){
                            refreshChart( "ManuInfo","Repair");
                        }
                        if ((paramComm=="Barcode")){
                            String barcode=mParams.get("Barcode").toString();
                            edt_barcode.setText(barcode);
                            searchBarcodeData(barcode);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        System.out.println(TAG+"onCreate-------------------------------------2");
    }


    //自动刷新数据
    private void refreshChart(String paramType,String paramFormName) {
        System.out.println(TAG+":准备刷新明细图表");
        String sqlcmd="Exec KeyPoint_GetChart @OperType='Chart',@QueryType='"+paramType+"',@FormName='"+paramFormName
                +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlcmd);
    }


    @Override
    public void onResume() {
        super.onResume();
        refreshChart( "ManuInfo","Repair");
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    {
        if (mFragmentCCallBack!=null)
        {
            fragmentParams.clear();
            fragmentParams.put("ParamComm","AllowScan");//命令;
            fragmentParams.put("ParamValue","Y");//参数;
            mFragmentCCallBack.FragmentCWorkAndTransParams(fragmentParams);
        } else Log.d("msg","mFragmentECallBack-----------空的咋办");
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        if (edt_barcode!=null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
            hideBottomUIMenu();
        }
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_c, container, false);
        InitView(root);
        System.out.println(this.getClass().getName()+"_onCreateView");
        return root;
    }
    //初始化;
    public void InitView(View view){
        view.findViewById(R.id.btn_cloth_size).setOnClickListener(this);
        btn_find=(Button)view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_Query=(Button)view.findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        btn_CheckAndonCall=view.findViewById(R.id.btn_CheckAndonCall);
        btn_CheckAndonCall.setOnClickListener(this);
        btn_editBarcode=(ImageButton)view.findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        btn_editBarcode.setFocusable(false);
        btn_editBarcode.setFocusableInTouchMode(false);
        txt_PSXX=view.findViewById(R.id.txt_PSXX);
        btn_BatchRepair=view.findViewById(R.id.btn_BatchRepair);
        btn_BatchRepair.setOnClickListener(this);
        //界面Edit;
        edt_barcode=(EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();

        txt_HintInfo=view.findViewById(R.id.txt_HintInfo);
        txt_OrderNo=view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=view.findViewById(R.id.txt_StyleNo);
        txt_PO=view.findViewById(R.id.txt_PO);
        txt_Color=view.findViewById(R.id.txt_Color);
        txt_Size=view.findViewById(R.id.txt_Size);
        txt_StyleSort=view.findViewById(R.id.txt_StyleSort);
        txt_Depart=view.findViewById(R.id.txt_Depart);
        btn_Select=view.findViewById(R.id.btn_Select);
        btn_Select.setOnClickListener(this);
        txt_ClampSendNum=view.findViewById(R.id.txt_ClampSendNum);
        txt_ClampOwenNum=view.findViewById(R.id.txt_ClampOwenNum);
        txt_TodayRepairNum=view.findViewById(R.id.txt_TodayRepairNum);
        txt_ClampRepairNum=view.findViewById(R.id.txt_ClampRepairNum);
        txt_NeedCheckInNum=view.findViewById(R.id.txt_NeedCheckInNum);
        btn_MarkBadPoint=view.findViewById(R.id.btn_MarkBadPoint);
        btn_MarkBadPoint.setOnClickListener(this);
        view.findViewById(R.id.btn_piece_size_search).setOnClickListener(this);
        btn_MarkBadPoint.setOnLongClickListener(this);
        btn_ClampState=view.findViewById(R.id.btn_ClampState);
        btn_ClampState.setOnClickListener(this);
        detailList=view.findViewById(R.id.colorsizeList);
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);
        //curToast.setGravity(Gravity.CENTER, 0, 0);
        mainCTColumnChart=view.findViewById(R.id.mainCTColumnChart);

    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }
    //刷新缸布列表;
    private void searchBarcodeData(String BarcodeParam)
    {
        if ((selDepartNo.length()==0)||(selOrderNo.length()==0)){
            curToast.setText("请先选择合约!");
            curToast.show();
        }
        NeedCheck=true;
        //执行SQL过程
        PrBarcode=BarcodeParam;
        if (selDepart.length()==0) {
            selDepart=curDepart;
            selDepartNo=curDepartNo;
        }
        String SqlComm = "Exec KeyPoint_RepairClipState @Barcode='" + BarcodeParam + "',@Department='" + selDepart + "',@OPERTYPE='SCANBARCODE',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    private void GetReason(String paramQuestion) {
        String SqlComm = "Exec KeyPoint_RepairGetReason @OPERTYPE='REASON',@Question='" + paramQuestion+"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            //成衣尺寸
            case R.id.btn_cloth_size:
                Intent clothsize=new Intent(getContext(),ClothSizeCheckActivity.class);
                Bundle paramBundle1 = new Bundle();
                paramBundle1.clear();
                paramBundle1.putString("LoginUserNo", curLoginUserNo);
                paramBundle1.putString("LoginUser",curLoginUser);
                paramBundle1.putString("CurDepartNo",curDepartNo);
                paramBundle1.putString("CurDepart",curDepart);
                paramBundle1.putString("ServiceUrl",curServiceUrl);
                paramBundle1.putString("ServiceDir",curServiceDir);
                if (selDepart.length()==0) {
                    selDepart=curDepart;
                    selDepartNo=curDepartNo;
                }
                paramBundle1.putString("selDepart",selDepart);
                paramBundle1.putString("selDepartNo",selDepartNo);
                paramBundle1.putString("selImageFile",selImageFile);
                paramBundle1.putString("selStyleNo",selStyleNo);
                paramBundle1.putString("selOrderNo",selOrderNo);
                paramBundle1.putString("selStyleSort",selStyleSort);
                paramBundle1.putString("selColor",selColor);
                paramBundle1.putString("selPO",selPO);
                paramBundle1.putString("selSize",selSize);
                paramBundle1.putString("TitleInv","疵点选择");
                paramBundle1.putString("NeedPos","NO");//图片标注
                paramBundle1.putInt("MaxPieces",MaxPieces);
                paramBundle1.putString("CPUID",CPUID);
                clothsize.putExtras(paramBundle1);
                startActivity(clothsize);
                break;
            //成衣尺寸查询
            case R.id.btn_piece_size_search:
                Intent outIntent23=new Intent(getContext(),ClothSizeSearchActivity.class);
                Bundle paramBundle23=new Bundle();
                paramBundle23.clear();
                paramBundle23.putString("LoginUserNo", curLoginUserNo);
                paramBundle23.putString("CurDepartNo", curDepartNo);
                outIntent23.putExtras(paramBundle23);
                startActivity(outIntent23);
                break;
            case R.id.btn_MarkBadPoint:
                MakeBadPoint("Large");
                break;
            case R.id.btn_ClampState:
                GetClampState(curDepartNo);
                break;
            case R.id.btn_Select:
                Intent intentStyleNoActivity=new Intent(getContext(),StyleNoActivity.class);
                Bundle paramBundle2 = new Bundle();
                paramBundle2.clear();
                paramBundle2.putString("LoginUserNo", curLoginUserNo);
                paramBundle2.putString("LoginUser",curLoginUser);
                paramBundle2.putString("CurDepartNo",curDepartNo);
                paramBundle2.putString("CurDepart",curDepart);
                paramBundle2.putString("ServiceUrl",curServiceUrl);
                paramBundle2.putString("ServiceDir",curServiceDir);
                if ((selDepart==null)||(selDepart.length()==0)) {
                    selDepart=curDepart;
                    selDepartNo=curDepartNo;
                }
                paramBundle2.putString("selDepart",selDepart);
                paramBundle2.putString("selDepartNo",selDepartNo);
                paramBundle2.putString("FormType","REPAIR");
                paramBundle2.putInt("DateNum",10);
                paramBundle2.putString("CPUID",CPUID);
                intentStyleNoActivity.putExtras(paramBundle2);
                startActivityForResult(intentStyleNoActivity,1000);
                break;
            case R.id.btn_Query:
                Intent intentQueryActivity=new Intent(getContext(),QueryActivity.class);
                Bundle paramBundle = new Bundle();
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("QueryTitle", "组检查询");
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                paramBundle.putString("NeedOrder","YES");
                intentQueryActivity.putExtras(paramBundle);
                startActivity(intentQueryActivity);
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;
            case R.id.btn_find:
                if (edt_barcode.getText().length()>0){
                    searchBarcodeData(edt_barcode.getText().toString());
                } else {
                    curToast.setText("请先输入条码!");
                    curToast.show();
                    return;
                }
                break;
            case R.id.btn_CheckAndonCall:
                CheckAndonCall();
                break;
            case R.id.btn_BatchRepair:

                showBatchRepair();
                break;
            case R.id.view_oneBtn:
            case R.id.view_twoBtn:
            case R.id.view_threeBtn:
            case R.id.view_fourBtn:
            case R.id.view_fiveBtn:
            case R.id.view_sixBtn:
            case R.id.view_sevenBtn:
            case R.id.view_eightBtn:
            case R.id.view_nineBtn:
            case R.id.view_zeroBtn:
                Button tmpBtn1 = v.findViewById(v.getId());
                edt_checkReal.getText().append(tmpBtn1.getText());
                break;
            case R.id.view_delBtn:
                if (edt_checkReal.getText().length() > 0) {
                    edt_checkReal.setSelection(edt_checkReal.getText().length());
                    int start = edt_checkReal.getSelectionStart();
                    edt_checkReal.getText().delete(start - 1, start);
                }
                break;
            case R.id.view_pointBtn:
                System.out.println("AindexOf:" + edt_checkReal.getText().toString().indexOf("."));
                if ((edt_checkReal.getText().toString().indexOf(".") == -1)&&(edt_checkReal.getText().toString().indexOf("/") == -1)) {
                    edt_checkReal.getText().append(".");
                }
                break;
            default:
                break;
        }
    }


    //修改包件数;
    private void showBatchRepair(){
        if ((selOrderNo==null)||(selOrderNo.length()==0)){
            curToast.setText("请先选择合约!");
            curToast.show();
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("批量返修");
        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(getContext()).inflate(R.layout.input_qcnumkey, null);
        //    设置我们自己定义的布局文件作为弹出框的Content
        builder.setView(view);
        edt_checkReal =view.findViewById(R.id.edt_checkReal);
        view_QCCode =view.findViewById(R.id.view_QCCode);
        reasonSpinner=view.findViewById(R.id.reasonSpinner);
        final Button view_dirtyBtn=view.findViewById(R.id.view_dirtyBtn);
        view_dirtyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view_QCCode.setText(view_dirtyBtn.getText().toString());
                GetReason(view_dirtyBtn.getText().toString());
            }
        });
        final Button view_oilBtn=view.findViewById(R.id.view_oilBtn);
        view_oilBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view_QCCode.setText(view_oilBtn.getText().toString());
                GetReason(view_dirtyBtn.getText().toString());
            }
        });
        view.findViewById(R.id.view_oneBtn).setOnClickListener(this);
        view.findViewById(R.id.view_twoBtn).setOnClickListener(this);
        view.findViewById(R.id.view_threeBtn).setOnClickListener(this);
        view.findViewById(R.id.view_fourBtn).setOnClickListener(this);
        view.findViewById(R.id.view_fiveBtn).setOnClickListener(this);
        view.findViewById(R.id.view_sixBtn).setOnClickListener(this);
        view.findViewById(R.id.view_sevenBtn).setOnClickListener(this);
        view.findViewById(R.id.view_eightBtn).setOnClickListener(this);
        view.findViewById(R.id.view_nineBtn).setOnClickListener(this);
        view.findViewById(R.id.view_zeroBtn).setOnClickListener(this);
        view.findViewById(R.id.view_delBtn).setOnClickListener(this);
        view.findViewById(R.id.view_pointBtn).setOnClickListener(this);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Field field = null;
                if (isNumer(edt_checkReal.getText().toString())){
                    if (Integer.parseInt(edt_checkReal.getText().toString())>999){
                        try {
                            field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                            field.setAccessible(true);
                            field.set(dialog, false);
                        } catch (NoSuchFieldException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                        curToast.setText("超出数量范围!");
                        curToast.show();
                        return;
                    }
                }
                if ((view_QCCode.getText().toString().length()>0)&&(edt_checkReal.getText().toString().trim().length()>0)) {
                    String checkReal = edt_checkReal.getText().toString().trim();
                    String QCCode = view_QCCode.getText().toString().trim();
                    String Reason = reasonSpinner.getSelectedItem().toString().trim();
                    String batchID = UUID.randomUUID().toString();
                    String SqlComm = "Exec KeyPoint_RepairClip @Barcode='R0123456789',@OrderNo='" + selOrderNo + "',@StyleNo='" + selStyleNo + "',@StyleSort='" + selStyleSort
                            + "',@PSXX='" + selPSXX + "',@Color='" + selColor + "',@Size='" + selSize + "',@PO='" + selPO + "',@DepartNo='" + selDepartNo + "',@ManuDepartNo='" + selManuDepartNo
                            + "',@Number='" + checkReal + "',@BatchID='" + batchID + "',@QCCode='" + QCCode+ "',@Reason='" + Reason
                            + "',@OPERTYPE='SCANBARCODE',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
                    //调用WebService过程并处理界面更新;
                    ReadSQLData(SqlComm);
                }
                else {
                    try {
                        field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                        field.setAccessible(true);
                        field.set(dialog, false);
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    curToast.setText("请选择疵点类型及输入件数！");
                    curToast.show();
                    return;
                }
                hideBottomUIMenu();
                try {
                    field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                    field.setAccessible(true);
                    field.set(dialog, true);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
        builder.setNeutralButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                System.out.println("a");
                try {
                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
                hideBottomUIMenu();

            }
        });
        builder.show();
    }
    //报到
    private void CheckAndonCall(){
        //执行SQL过程
        String SqlComm="Exec KeyPoint_RepairCheckAndonCall @Department='" + curDepart + "',@OPERTYPE='ANDONCALL',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //坏点记录根据类型显示不同界面
    private void MakeBadPoint(String paramClipType){
        if ((selDepartNo.length()==0)||(selStyleNo.length()==0)){
            curToast.setText("请先选择合约!");
            curToast.show();
            return;
        }
        Intent intentQuestionActivity=new Intent(getContext(),QuestionActivity.class);
        Bundle paramBundle1 = new Bundle();
        paramBundle1.clear();
        paramBundle1.putString("LoginUserNo", curLoginUserNo);
        paramBundle1.putString("LoginUser",curLoginUser);
        paramBundle1.putString("CurDepartNo",curDepartNo);
        paramBundle1.putString("CurDepart",curDepart);
        paramBundle1.putString("ServiceUrl",curServiceUrl);
        paramBundle1.putString("ServiceDir",curServiceDir);
        if (selDepart.length()==0) {
            selDepart=curDepart;
            selDepartNo=curDepartNo;
        }
        paramBundle1.putString("selDepart",selDepart);
        paramBundle1.putString("selDepartNo",selDepartNo);
        paramBundle1.putString("selImageFile",selImageFile);
        paramBundle1.putString("selStyleNo",selStyleNo);
        paramBundle1.putString("selOrderNo",selOrderNo);
        paramBundle1.putString("selStyleSort",selStyleSort);
        paramBundle1.putString("ClipType",paramClipType);
        paramBundle1.putString("TitleInv","疵点选择");
        System.out.println("curDepartNo.substring(0,1):"+curDepartNo.substring(0,1)+"  old:"+curDepartNo);
        if (curDepartNo.substring(0,1).equals("6"))
            paramBundle1.putString("NeedPos","YES");//图片标注
        else
            paramBundle1.putString("NeedPos","NO");//图片标注
        paramBundle1.putInt("MaxPieces",MaxPieces);
        paramBundle1.putString("CPUID",CPUID);
        intentQuestionActivity.putExtras(paramBundle1);
        startActivityForResult(intentQuestionActivity,2000);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("requestCode:"+requestCode+" resultCode:"+resultCode);
        //选合约返回
        if ((requestCode==1000)&&(resultCode==1001)){
            setEditBarcodeFocus();
            //获取登陆参数
            Bundle paramBundle = data.getExtras();
            selDepart=paramBundle.getString("selDepart");
            selDepartNo=paramBundle.getString("selDepartNo");
            selOrderNo=paramBundle.getString("selOrderNo");
            selStyleNo=paramBundle.getString("selStyleNo");
            selStyleSort=paramBundle.getString("selStyleSort");
            selPO=paramBundle.getString("selPO");
            selColor=paramBundle.getString("selColor");
            selSize=paramBundle.getString("selSize");
            selPSXX=paramBundle.getString("selPSXX");
            selManuDepartNo=paramBundle.getString("selManuDepartNo");
            selManuDepart=paramBundle.getString("selManuDepart",selDepart);
            if (selManuDepart.length()==0) selManuDepart=selDepart;
            selImageFile=paramBundle.getString("selImageFile");
            //填充界面
            txt_OrderNo.setText(selOrderNo);
            txt_StyleNo.setText(selStyleNo);
            txt_StyleSort.setText(selStyleSort);
            txt_PO.setText(selPO);
            txt_Size.setText(selSize);
            txt_Color.setText(selColor);
            txt_Depart.setText(selManuDepart);
            txt_PSXX.setText(selPSXX);
            //获取图片及部位
            System.out.println("selImageFile:"+selImageFile);
            if (selImageFile.length()>0) GetStyleInfo(selImageFile);
            getPart(selOrderNo,selStyleNo,selStyleSort);
        }
        //选疵点返回
        if ((requestCode==2000)&&(resultCode==2001)){
            //获取登陆参数
            Bundle paramBundle = data.getExtras();
            try {
                System.out.println("onActivityResult1");
                questionJson= new JSONArray(paramBundle.getString("questionJson"));
                System.out.println("onActivityResult2");
                System.out.println(questionJson);
                String batchID= UUID.randomUUID().toString();
                SubmitQuestion(batchID);
            } catch (JSONException e) {
                System.out.println("onActivityResult："+e.getMessage());
                e.printStackTrace();
            }
        }

        hideBottomUIMenu();
    }

    //获取图形及部位数据
    private void GetStyleInfo(String paramImageFile) {
        String imgfilepath = getActivity().getCacheDir().toString();
        File file = new File(imgfilepath + "/" + paramImageFile);
        System.out.println("图片文件路径:" + imgfilepath + "/" + paramImageFile);
        //判断图片是否存在，如果不存在则从网络获取;
        if (file.exists() == true) {
            Log.d(TAG, "本地有取图片---------------");
            //从本地取图片
            //Bitmap bitmap = getLoacalBitmap(imgfilepath + "/" + curImageFileName);
            //imageLayout.setImgBg(bitmap);
        } else {
            Log.d(TAG, "发消息从网络获取图片---------------");
            //Drawable drawable = getResources().getDrawable(R.mipmap.err404);
            //BitmapDrawable errBitDraw = (BitmapDrawable) drawable;
            //imageLayout.setImgBg(errBitDraw.getBitmap());
            //发前消息，获取图片;
            Message msg = new Message();
            msg.what = msgGetImg;
            fragmentHandler.removeMessages(msg.what);
            fragmentHandler.sendMessage(msg);
        }
    }

    /**
     * @param @param  url 本地路径
     * @param @return
     * @return Bitmap
     * @throws
     * @Title: getLoacalBitmap
     * @Description: 加载本地图片
     */
    public Bitmap getLoacalBitmap(String url) {
        if (url != null) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(url);
                return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fis = null;
                }
            }
        } else {
            return null;
        }
    }


    /**
     * 保存文件
     */
    public void saveBitmap(Bitmap bm, String fileName) {
        //获取MainActivity
        MainActivity activity = (MainActivity) getActivity();
        //String imgfilepath=activity.SaveFilePath+activity.SaveIMGFolder;
        String imgfilepath = activity.getCacheDir().toString();
        Log.d("saveBitmap", "imgfilepath:" + imgfilepath);
        File f = new File(imgfilepath, fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            if (fileName.toUpperCase().indexOf("PNG") > 0)
                bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            if ((fileName.toUpperCase().indexOf("JPG") > 0) || (fileName.toUpperCase().indexOf("JPEG") > 0))
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.i("saveBitmap", fileName+"已经保存成功");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //从字符串转颜色
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor=Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                String tmpValue;
                //任意消息来均置焦点
                int msgId = msg.what;
                System.out.println("收到的消息是："+msg.what);
                try {
                    switch (msgId) {
                        case MSG_Spinner:
                            ArrayList<String>list=new ArrayList<String>();
                            if (spinnerJSON!=null&&spinnerJSON.length()>0){
                                System.out.println("spinnerJSON:"+spinnerJSON);
                                for (int i=0;i<spinnerJSON.length();i++){
                                    if (spinnerJSON.optJSONObject(i).has("Reason"))
                                        list.add(spinnerJSON.optJSONObject(i).getString("Reason"));
                                }
                                SpinnerAdapter adapter = new ArrayAdapter<String>(getContext(),R.layout.spinner_item,list);
                                reasonSpinner.setAdapter(adapter);
                            }
                            break;
                        case MSG_ERRMSG:
                            Bundle bundle=msg.getData();
                            System.out.println(bundle);
                            String SQLExcept=bundle.getString("SQLExcept");
                            String SQLMessage=bundle.getString("SQLMessage");
                            curToast.setText(SQLMessage);
                            curToast.show();
                        case msgFocusBarcode:
                            setEditBarcodeFocus();
                            break;
                        case MSG_SCANBARCODE:
                            setEditBarcodeFocus();
                            if (resultJSON!=null){
                                if (resultJSON.length()>0){
                                    if (resultJSON.optJSONObject(0).has("ClipState")==true) {
                                        if (resultJSON.optJSONObject(0).getString("ClipState").toUpperCase().equals("SEND")){
                                            if ((resultJSON.optJSONObject(0).has("ClipType")==true)&&(resultJSON.optJSONObject(0).has("MaxPieces")==true))
                                            {
                                                //调用返修疵点选择
                                                MaxPieces=resultJSON.optJSONObject(0).getInt("MaxPieces");
                                                MakeBadPoint(resultJSON.optJSONObject(0).getString("ClipType"));
                                            }
                                        }
                                    }
                                }
                                fillFormtext();
                            }
                            break;
                        case MSG_CLIPVIEW:
                            //显示明细数据
                            detailList.setAdapter(detailListAdapter);
                            break;
                        case msgGetImg:
                            getImage(selImageFile, selOrderNo, selStyleNo, selStyleSort);
                            break;
                        case msgPutQuestionOK:
                        case msgPutQuestionErr:
                            Bundle bdl = msg.getData();
                            String result = bdl.getString("resultJson");
                            try {
                                resultJSON = new JSONArray(result);
                                System.out.println("resultJson:"+resultJSON);
                                fillFormtext();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            curToast.setText(bdl.getString("msg"));
                            curToast.show();
                            break;
                        case MSG_ANDONCALL:
                            fillFormtext();
                            break;
                        case MSG_ChartOver:
                            showBalanceChart();
                            break;
                        default:
                            break;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    };

    /**
     *
     */
    //显示图表;
    private void showBalanceChart()
    {
        Log.d(TAG,"showBalanceChart()----------------------------------------------------->1");
        int reindex=0;
        float WorkCT=100;
        //初始化工序列表;
        List<AxisValue> axisValues = new ArrayList<AxisValue>();
        List<Column> columns = new ArrayList<Column>();
        List<SubcolumnValue> subcolValues;
        List<Line> lines = new ArrayList<Line>();
        List<PointValue> aPointValues=new ArrayList<PointValue>();
        List<PointValue> aLineValues=new ArrayList<PointValue>();
        try {
            for (int i=0;i<chartJSON.length();i++){
                String colLable=chartJSON.optJSONObject(i).getString("TitleCaption");
                float colValue=chartJSON.optJSONObject(i).getLong("ColValue");
                float lineValue=chartJSON.optJSONObject(i).getLong("LineValue");
                //多个子柱对比时可加多个值;
                subcolValues=new ArrayList<SubcolumnValue>();
                subcolValues.add(new SubcolumnValue(colValue, ChartUtils.COLORS[0]));
                //添加列并在柱子上方加值显示;不仅仅是在选择时显示;
                columns.add(new Column(subcolValues).setHasLabelsOnlyForSelected(true).setHasLabels(true));
                aPointValues.add(new PointValue(i, lineValue));
                //X轴标签;
                axisValues.add(new AxisValue(i).setLabel(colLable));
                reindex++;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d(TAG,"showBalanceChart()----------------------------------------------------->2");
        //创建柱状图数据;
        ColumnChartData columnChartData = new ColumnChartData(columns);
        //线条图
        Line line = new Line(aPointValues);
        line.setColor(ChartUtils.COLORS[1]);
        line.setCubic(isCubic);
        line.setHasLabels(hasLabels);
        line.setHasLines(hasLines);
        line.setHasPoints(false);
        lines.add(line);
        //创建线形数据;
        LineChartData lineChartData = new LineChartData(lines);
        //创建图形数据;
        mainCTColumnData=new ComboLineColumnChartData(columnChartData, lineChartData);
        //国形控制格式;
        if (hasAxes) {
            Axis axisX = new Axis();
            Axis axisY = new Axis().setHasLines(true);
            axisX.setName("时间段");
            axisY.setName("返修数");
            axisY.setLineColor(getResources().getColor(R.color.linebackcolor));
            axisX.setHasTiltedLabels(true);
            axisX.setHasSeparationLine(false);
            axisX.setValues(axisValues);
            axisY.setTextColor(getResources().getColor(R.color.text_main));
            axisX.setTextColor(getResources().getColor(R.color.text_main));
            mainCTColumnData.setAxisXBottom(axisX);
            mainCTColumnData.setAxisYLeft(axisY);
        } else {
            mainCTColumnData.setAxisXBottom(null);
            mainCTColumnData.setAxisYLeft(null);
        }
        //显示图表;
        mainCTColumnChart.setComboLineColumnChartData(mainCTColumnData);
        //仅横向允许放大;
        mainCTColumnChart.setValueSelectionEnabled(false);
        mainCTColumnChart.setZoomEnabled(false);
        mainCTColumnChart.setZoomType(ZoomType.HORIZONTAL);
        //判断是否有数据，如果无数据，则调用数据刷新;
    }
    //获取部位数据
    private void getPart(String selOrderNo, String selStyleNo, String selStyleSort) {
        String SqlComm="Exec KeyPoint_RepairGetPart @OrderNo='" + selOrderNo + "',@StyleNo='" + selStyleNo+ "',@StyleSort='" + selStyleSort
                + "',@OPERTYPE='GetPart',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }
    //获取图片;
    private void getImage(final String paramImageFile,final String paramOrderNo,final String paramStyleNo,final String paramStyleSort)
    {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    ResultSet re = DBUtil.OpenSQL("Exec KeyPoint_GetStyleImg @OrderNo='"+paramOrderNo+"',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort + "'");
                    if (re != null) {
                        re.next();
                        //使用Blob对象接收数据库里的图片
                        if (re.findColumn("ImgResult") > -1) {
                            String ImgResult = re.getString("ImgResult");
                            if (ImgResult.equals("OK")) {
                                java.sql.Blob imgBlob = re.getBlob("ImgFile");
                                //获取Blob对象的二进制流;
                                InputStream imgInS = imgBlob.getBinaryStream();
                                //加载一个网络图片
                                Bitmap bitmap = BitmapFactory.decodeStream(imgInS);
                                //保存图片;
                                saveBitmap(bitmap, paramImageFile);
                            }
                        }
                    }
                    re.getStatement().getConnection().close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(run).start();
    }

    //保存数据;
    private void SubmitQuestion(final String paramBatchID)
    {
        System.out.println("SubmitQuestion:"+paramBatchID);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    String SqlText="";
                    Log.d("SubmitQuestion","1");
                    for (int i=0;i<questionJson.length();i++){
                        String RowNo=questionJson.optJSONObject(i).getString("RowNo");
                        String QuestionCodes=questionJson.optJSONObject(i).getString("QuestionCodes");
                        String PosX=questionJson.optJSONObject(i).getString("PosX");
                        String PosY=questionJson.optJSONObject(i).getString("PosY");
                        String PartName=questionJson.optJSONObject(i).getString("PartName");
                        String Reason=questionJson.optJSONObject(i).getString("Reason");
                        if (i<questionJson.length()) {
                            SqlText = "Exec KeyPoint_RepairClipDe @Barcode='" + PrBarcode + "',@OrderNo='" + selOrderNo + "',@StyleNo='" + selStyleNo + "',@StyleSort='" + selStyleSort
                                    + "',@PSXX='" + selPSXX + "',@Color='" + selColor + "',@Size='" + selSize + "',@PO='" + selPO + "',@DepartNo='" + selDepartNo+ "',@ManuDepartNo='" + selManuDepartNo
                                    + "',@RowNo='" + RowNo + "',@QuestionCodes='" + QuestionCodes + "',@PosX='" + PosX + "',@PosY='" + PosY + "',@PartName='" + PartName+ "',@Reason='" + Reason + "',@BatchID='" + paramBatchID
                                    + "',@OPERTYPE='SCANBARCODE',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
                        }
                        Log.d("SubmitQuestion",SqlText);
                        DBUtil.QuerySQL2JSON(SqlText);
                    }
                    Log.d("SubmitQuestion","2");
                    //消息提醒出错;
                    SqlText = "Exec KeyPoint_RepairClip @Barcode='" + PrBarcode + "',@OrderNo='" + selOrderNo + "',@StyleNo='" + selStyleNo + "',@StyleSort='" + selStyleSort
                            + "',@PSXX='" + selPSXX + "',@Color='" + selColor + "',@Size='" + selSize + "',@PO='" + selPO + "',@DepartNo='" + selDepartNo+ "',@ManuDepartNo='" + selManuDepartNo
                            + "',@Number='" + questionJson.length()  + "',@BatchID='" + paramBatchID
                            + "',@OPERTYPE='SCANBARCODE',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
                    Log.d("SubmitQuestion2",SqlText);
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SqlText);
                    if (jsonArray != null) {
                        //使用Blob对象接收数据库里的图片
                        if (jsonArray.length()>0){
                            if (jsonArray.optJSONObject(0).has("Result")){
                                if (jsonArray.optJSONObject(0).getString("Result").equals("OK")){
                                    //发前消息，获取图片;
                                    Message msg = new Message();
                                    msg.what = msgPutQuestionOK;
                                    Bundle bdl=new Bundle();
                                    bdl.putString("msg","保存成功！");
                                    bdl.putString("resultJson",jsonArray.toString());
                                    msg.setData(bdl);
                                    fragmentHandler.removeMessages(msg.what);
                                    fragmentHandler.sendMessage(msg);
                                }else
                                {
                                    //发前消息，获取图片;
                                    Message msg = new Message();
                                    msg.what = msgPutQuestionErr;
                                    Bundle bdl=new Bundle();
                                    bdl.putString("msg","保存失败！");
                                    bdl.putString("resultJson",jsonArray.toString());
                                    msg.setData(bdl);
                                    fragmentHandler.removeMessages(msg.what);
                                    fragmentHandler.sendMessage(msg);
                                }
                            }
                        } else{
                            //发前消息，获取图片;
                            Message msg = new Message();
                            msg.what = msgPutQuestionErr;
                            Bundle bdl=new Bundle();
                            bdl.putString("msg",SqlText+"未返回任何值！");
                            msg.setData(bdl);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    //发前消息，获取图片;
                    Message msg = new Message();
                    msg.what = msgPutQuestionErr;
                    Bundle bdl=new Bundle();
                    bdl.putString("msg",e.getMessage());
                    msg.setData(bdl);
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        };
        new Thread(run).start();
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println(SQLComm);
        Runnable run = new Runnable() {
            @Override
            public synchronized  void run() {
                try {
                    reentrantLock.lock();
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        System.out.println(jsonArray);
                        String OPERTYPE = "";
                        if (jsonArray.optJSONObject(0).has("OPERTYPE") == true)
                            OPERTYPE = jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (jsonArray.optJSONObject(0).has("OperType") == true)
                            OPERTYPE = jsonArray.optJSONObject(0).getString("OperType");
                        if (OPERTYPE.toUpperCase().equals("SCANBARCODE")) {
                            resultJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_SCANBARCODE;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("CLIPVIEW")) {
                            detailJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_CLIPVIEW;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("GETPART")) {
                            partJson = jsonArray;
                            //将数据放到Part表中
                            if (tmpdb == null) OpenCreateDB();
                            try {
                                tmpdb.execSQL("Delete from PartDefine");
                                for (int i = 0; i < partJson.length(); i++) {
                                    tmpdb.execSQL("Insert into PartDefine(PartName,PosX,PosY) values(?,?,?)",
                                            new Object[]{partJson.optJSONObject(i).getString("PartName"),
                                                    partJson.optJSONObject(i).getLong("PosX"),
                                                    partJson.optJSONObject(i).getLong("PosY"),
                                            });
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                curToast.setText("部位定义数据暂存完成:\r\b" + e.getMessage());
                                curToast.show();
                            }
                        }
                        if (OPERTYPE.toUpperCase().equals("REASON")){
                            spinnerJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_Spinner;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("ANDONCALL")) {
                            resultJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ANDONCALL;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("CHART")) {
                            chartJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ChartOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept")) {
                            System.out.println("Enter SqlExcept");
                            //显示预排单;
                            Message msg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("SQLExcept", jsonArray.optJSONObject(0).getString("SQLExcept"));
                            bundle.putString("SQLMessage", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            msg.what = MSG_ERRMSG;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                    }else {
                        //显示预排单;
                        Message msg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("SQLExcept", "ErrInfo");
                        bundle.putString("SQLMessage", "未返回任何数据!");
                        msg.setData(bundle);
                        msg.what = MSG_ERRMSG;
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    reentrantLock.unlock();
                }finally {
                    reentrantLock.unlock();
                }
            }
        };
        new Thread(run).start();
    }


    //打开数据库
    public void OpenCreateDB(){
        if (tmpdb==null) {
            MainActivity activity = (MainActivity) getActivity();
            tmpdb = activity.mainDB;
        }
    }


    //清除界面显示内容
    private void clearFormText(){
        txt_HintInfo.setText("");
        txt_OrderNo.setText("");
        txt_StyleNo.setText("");
        txt_PO.setText("");
        txt_Color.setText("");
        txt_Size.setText("");
        txt_StyleSort.setText("");
        txt_PSXX.setText("");
        txt_HintInfo.setText("");
    }

    //填充界面显示内容;
    private void fillFormtext(){
        if (resultJSON.length()>0)
        {
            try {
                //别的参数刷新
                if (resultJSON.getJSONObject(0).has("OrderNo")==true) txt_OrderNo.setText(resultJSON.getJSONObject(0).getString("OrderNo"));
                if (resultJSON.getJSONObject(0).has("StyleNo")==true) txt_StyleNo.setText(resultJSON.getJSONObject(0).getString("StyleNo"));
                if (resultJSON.getJSONObject(0).has("PO")==true) txt_PO.setText(resultJSON.getJSONObject(0).getString("PO"));
                if (resultJSON.getJSONObject(0).has("Color")==true) txt_Color.setText(resultJSON.getJSONObject(0).getString("Color"));
                if (resultJSON.getJSONObject(0).has("Size")==true) txt_Size.setText(resultJSON.getJSONObject(0).getString("Size"));
                if (resultJSON.getJSONObject(0).has("StyleSort")==true) txt_StyleSort.setText(resultJSON.getJSONObject(0).getString("StyleSort"));
                if (resultJSON.getJSONObject(0).has("PSXX")==true) txt_PSXX.setText(resultJSON.getJSONObject(0).getString("PSXX"));

                if (resultJSON.getJSONObject(0).has("LoadDetail")==true) {
                    if (resultJSON.getJSONObject(0).getString("LoadDetail").toUpperCase().equals("YES"))  GetClampState(curDepartNo);
                }

                if (resultJSON.getJSONObject(0).has("ClampSendNum")==true) txt_ClampSendNum.setText(resultJSON.getJSONObject(0).getString("ClampSendNum"));
                if (resultJSON.getJSONObject(0).has("ClampOwenNum")==true) txt_ClampOwenNum.setText(resultJSON.getJSONObject(0).getString("ClampOwenNum"));
                if (resultJSON.getJSONObject(0).has("ClampRepairNum")==true) txt_ClampRepairNum.setText(resultJSON.getJSONObject(0).getString("ClampRepairNum"));
                if (resultJSON.getJSONObject(0).has("TodayRepairNum")==true) txt_TodayRepairNum.setText(resultJSON.getJSONObject(0).getString("TodayRepairNum"));
                if (resultJSON.getJSONObject(0).has("NeedCheckInNum")==true) txt_NeedCheckInNum.setText(resultJSON.getJSONObject(0).getString("NeedCheckInNum"));

                if (resultJSON.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(resultJSON.getJSONObject(0).getString("HintInfo"));
                if (resultJSON.getJSONObject(0).has("ErrInfo")==true)
                {
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle("系统提示").setMessage(resultJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideBottomUIMenu();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


    }
    //获取订单
    private void GetClampState(String paramDepartNo) {
        try {
            detailJSON=new JSONArray("[]");
            detailListAdapter.notifyDataSetChanged();
            //显示明细数据
            detailList.setAdapter(detailListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_RepairClipView @DepartNo='" + paramDepartNo + "',@OPERTYPE='ClipView',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }
    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.fragment_c_listhead, null, false);
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                TextView tv;
                if (detailJSON.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = detailJSON.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                tv= view.findViewById(R.id.item_Barcode);
                if ((tv!=null)&&(detailJSON.optJSONObject(position).has("Barcode") == true)){
                    tv.setText(detailJSON.optJSONObject(position).getString("Barcode"));
                    ((TextView) view.findViewById(R.id.item_Barcode)).setTextColor(color);
                }
                tv= view.findViewById(R.id.item_Depart);
                if ((tv!=null)&&(detailJSON.optJSONObject(position).has("Depart") == true)){
                    tv.setText(detailJSON.optJSONObject(position).getString("Depart"));
                    tv.setTextColor(color);
                }
                tv= view.findViewById(R.id.item_OrderNo);
                if ((tv!=null)&&(detailJSON.optJSONObject(position).has("OrderNo") == true)){
                    tv.setText(detailJSON.optJSONObject(position).getString("OrderNo"));
                    tv.setTextColor(color);
                }
                tv= view.findViewById(R.id.item_Barcode);
                if ((tv!=null)&&(detailJSON.optJSONObject(position).has("Barcode") == true)){
                    tv.setText(detailJSON.optJSONObject(position).getString("Barcode"));
                    tv.setTextColor(color);
                }
                tv= view.findViewById(R.id.item_StyleNo);
                if ((tv!=null)&&(detailJSON.optJSONObject(position).has("StyleNo") == true)){
                    tv.setText(detailJSON.optJSONObject(position).getString("StyleNo"));
                    tv.setTextColor(color);
                }
                tv= view.findViewById(R.id.item_QuestionCode);
                if ((tv!=null)&&(detailJSON.optJSONObject(position).has("QuestionCode") == true)){
                    tv.setText(detailJSON.optJSONObject(position).getString("QuestionCode"));
                    tv.setTextColor(color);
                }
                tv= view.findViewById(R.id.item_UseMinute);
                if ((tv!=null)&&(detailJSON.optJSONObject(position).has("UseMinute") == true)){
                    tv.setText(detailJSON.optJSONObject(position).getString("UseMinute"));
                    tv.setTextColor(color);
                }
                tv= view.findViewById(R.id.item_ClipType);
                if ((tv!=null)&&(detailJSON.optJSONObject(position).has("ClipType") == true)){
                    tv.setText(detailJSON.optJSONObject(position).getString("ClipType"));
                    tv.setTextColor(color);
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailListAdapter_position:"+position);
            return view;
        }
    }


    @Override
    public void onStart() {
        super.onStart();
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        setEditBarcodeFocus();
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden==false){
            //读配置文件
            System.out.println("Read Set AutoSave");
            SharedPreferences settings = getActivity().getSharedPreferences("Settings", MODE_PRIVATE);

        }
    }
}
